package com.industrial.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;

import com.industrial.app.domain.formal.FourGyPower;
import com.industrial.app.excel.entity.FourGyPowerExcelEntity;
import com.industrial.app.excel.listener.ReadSpecifyRowListener;
import com.industrial.app.mapper.FourGyPowerFormalMapper;
import com.industrial.app.mapper.FourGyPowerMapper;
import com.industrial.app.service.IFourGyPowerService;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 4省工业用电Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-22
 */
@Service
public class FourGyPowerServiceImpl implements IFourGyPowerService
{
    @Autowired
    private FourGyPowerMapper fourGyPowerMapper;

    @Autowired
    private FourGyPowerFormalMapper fourGyPowerFormalMapper;

    @Value("${app.file-upload-path}")
    private String fileUploadPath;

    /**
     * 查询4省工业用电
     *
     * @param baseId 4省工业用电主键
     * @return 4省工业用电
     */
    @Override
    public FourGyPower selectFourGyPowerByBaseId(String baseId)
    {
        return fourGyPowerMapper.selectFourGyPowerByBaseId(baseId);
    }

    /**
     * 查询4省工业用电列表
     *
     * @param fourGyPower 4省工业用电
     * @return 4省工业用电
     */
    @Override
    public List<FourGyPower> selectFourGyPowerList(FourGyPower fourGyPower)
    {
        return fourGyPowerMapper.selectFourGyPowerList(fourGyPower);
    }

    /**
     * 新增4省工业用电
     *
     * @param fourGyPower 4省工业用电
     * @return 结果
     */
    @Override
    public int insertFourGyPower(FourGyPower fourGyPower)
    {
        return fourGyPowerMapper.insertFourGyPower(fourGyPower);
    }

    /**
     * 修改4省工业用电
     *
     * @param fourGyPower 4省工业用电
     * @return 结果
     */
    @Override
    public int updateFourGyPower(FourGyPower fourGyPower)
    {
        return fourGyPowerMapper.updateFourGyPower(fourGyPower);
    }

    /**
     * 批量删除4省工业用电
     *
     * @param baseIds 需要删除的4省工业用电主键
     * @return 结果
     */
    @Override
    public int deleteFourGyPowerByBaseIds(String[] baseIds)
    {
        return fourGyPowerMapper.deleteFourGyPowerByBaseIds(baseIds);
    }

    /**
     * 删除4省工业用电信息
     *
     * @param baseId 4省工业用电主键
     * @return 结果
     */
    @Override
    public int deleteFourGyPowerByBaseId(String baseId)
    {
        return fourGyPowerMapper.deleteFourGyPowerByBaseId(baseId);
    }

    /**
     * @param file
     * @return
     */
    @Override
    public AjaxResult importExcelFile(MultipartFile multipartFile) {
        try{
            List<FourGyPower> oldData = fourGyPowerMapper.selectFourGyPowerList(new FourGyPower());
            if(oldData != null && !oldData.isEmpty()){
                return AjaxResult.warn("导入之前需要先清空历史数据");
            }
            /* 上传文件的路径 */
            String absoluteExcelPath = fileUploadPath + File.separator + IdUtil.simpleUUID() + ".xlsx";
            File file = new File(absoluteExcelPath);
            if(!file.exists()){
                FileUtil.touch(file);
            }
            multipartFile.transferTo(file);
//            String uploadPath = FileUploadUtils.upload(AppConfig.getProfile(),multipartFile);
//            String absoluteExcelPath = FileUploadUtils.replaceAbsolutePath(uploadPath);
            //读取EXCEL中的数据
            List<FourGyPowerExcelEntity> excelDataArgs = EasyExcel.read(absoluteExcelPath).head(FourGyPowerExcelEntity.class).headRowNumber(4).sheet().doReadSync();
            //读取出年份，用于计算年份

            ReadSpecifyRowListener listener = new ReadSpecifyRowListener(2);
            ExcelReader build = EasyExcelFactory.read(absoluteExcelPath, listener).headRowNumber(2).build();
            build.readAll();
            Map dateMap = listener.getData();
            if(dateMap == null || dateMap.isEmpty()){
                return AjaxResult.warn("没有找到日期");
            }

            List<String> rqList = new ArrayList<>();
            for(Object item : dateMap.entrySet()){
                Map.Entry entry = (Map.Entry) item;
                Object value = entry.getValue();
                if(!Objects.isNull(value)){
                    rqList.add((String)value);
                }
            }
            if(rqList.isEmpty()){
                return AjaxResult.warn("没有找到日期");
            }
            Integer maxYear = rqList.stream().map(item -> {
                String str = StrUtil.removeSuffix(item, "年");
                return Integer.valueOf(str);
            }).max(Integer::compare).get();

            List<FourGyPower> list = new ArrayList<>();
            for(FourGyPowerExcelEntity item : excelDataArgs){
                FourGyPower fourGyPower = new FourGyPower();
                BeanUtil.copyProperties(item,fourGyPower);
                fourGyPower.setYears(String.valueOf(maxYear + 1));
                fourGyPower.setBaseId(IdUtil.simpleUUID());
                String area = item.getArea();
                String areaCode = DictUtils.getDictValue("import_area", StringUtils.trimAllWhitespace(area));
                fourGyPower.setArea(areaCode);
                list.add(fourGyPower);
            }
            if(!list.isEmpty()){
                fourGyPowerMapper.batchInsertBizFourGyPower(list);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
            return AjaxResult.warn("未知错误");
        }
        return AjaxResult.success("导入成功");
    }

    /**
     * <p>
     * 清空所有的4省工业用电数据
     * </p>
     *
     * @return
     */
    @Override
    public void clearAllTableData() {
        fourGyPowerMapper.clearAllTableData();
    }

    /**
     * @return
     */
    @Override
    public boolean transferDataInOneClick() {
        try{
            List<FourGyPower> result = fourGyPowerMapper.selectBizFourGyPowerAllData();

            int count = 0;
            List<FourGyPower> list = new ArrayList<>();
            for(FourGyPower item : result){
                list.add(item);
                count++;
                if(count >= 100){
                    fourGyPowerFormalMapper.batchInsertBizFourGyPowerFormal(list);
                    list.clear();
                }
            }

            if(!list.isEmpty()){
                fourGyPowerFormalMapper.batchInsertBizFourGyPowerFormal(list);
                list.clear();
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
